package leetcode.datastructure.trie;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Program225Trie {
    //  根节点是个空对象
    private Program225Trie[] children;
    private boolean isEndOfWord;

    public Program225Trie() {
        children = new Program225Trie[26]; // 只处理小写字母
        isEndOfWord = false;
    }

    public void insert(String word) {
        Program225Trie trie = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (trie.children[index] == null) {
                trie.children[index] = new Program225Trie();
            }
            trie = trie.children[index];
        }
        // 调整最后一位的状态
        trie.isEndOfWord = true;
    }

    public boolean search(String word) {
        Program225Trie trie = this;
        for (int i = 0; i < word.length(); i++) {
            char ch = word.charAt(i);
            int index = ch - 'a';
            if (trie.children[index] == null) {
                return false;
            }
            trie = trie.children[index];
        }
        return trie.isEndOfWord;
    }

    public boolean startsWith(String prefix) {
        Program225Trie trie = this;
        for (int i = 0; i < prefix.length(); i++) {
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if (trie.children[index] == null) {
                return false;
            }
            trie = trie.children[index];
        }
        return true;
    }

    public static void main(String[] args) {
        Program225Trie trie = new Program225Trie();
        trie.insert("apple");
        System.out.println(trie.search("apple"));;   // 返回 True
        System.out.println(trie.search("app"));;     // 返回 False
        System.out.println(trie.startsWith("app"));; // 返回 True
        trie.insert("app");
        System.out.println(trie.search("app"));;     // 返回 True
    }
}
